<template>
  <div class="device-management-container">
    <!-- 页面头部 -->
    <header class="page-header">
      <div class="header-content">
        <h1>门禁设备管理</h1>
        <p>管理小区内所有门禁相关设备的信息与状态</p>
      </div>
      <el-button type="primary" @click="handleAddDevice" class="add-device-btn">
        <i class="el-icon-plus"></i> 新增设备
      </el-button>
    </header>

    <!-- 主内容区 -->
    <main class="main-content">
      <!-- 筛选与操作区 -->
      <div class="filter-and-actions">
        <el-input
          v-model="filterForm.name"
          placeholder="设备名称"
          class="filter-item"
          size="small"
        ></el-input>
        <div class="row">
          <el-select
            v-model="filterForm.type"
            placeholder="设备类型"
            class="filter-item"
            size="small"
          >
            <el-option label="全部类型" value=""></el-option>
            <el-option
              v-for="type in deviceTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            ></el-option>
          </el-select>
          <el-select
            v-model="filterForm.status"
            placeholder="设备状态"
            class="filter-item"
            size="small"
          >
            <el-option label="全部状态" value=""></el-option>
            <el-option
              v-for="status in deviceStatuses"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            ></el-option>
          </el-select>
        </div>
        <div class="row">
          <el-button type="primary" size="small" class="filter-item" @click="handleFilter">
            <i class="el-icon-search"></i> 筛选
          </el-button>
          <el-button size="small" class="filter-item" @click="resetFilter">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </div>
      </div>

      <!-- 设备状态统计 -->
      <div class="status-stats">
        <div
          class="stat-card"
          :class="status.colorClass"
          v-for="status in deviceStatuses"
          :key="status.value"
        >
          <div class="stat-info">
            <p class="stat-label">{{ status.label }}</p>
            <p class="stat-count">{{ getStatusCount(status.value) }}</p>
          </div>
          <div class="stat-icon">
            <i :class="status.icon"></i>
          </div>
        </div>
      </div>

      <div class="device-table-container">
        <el-table
          :data="filteredDevices"
          border
          stripe
          style="width: 100%"
          v-loading="loading"
          element-loading-text="加载中..."
        >
          <el-table-column
            prop="name"
            label="设备名称"
            width="180"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="code"
            label="设备编码"
            width="160"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="type"
            label="设备类型"
            width="140"
            :formatter="formatDeviceType"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="location"
            label="安装位置"
            width="180"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="ipAddress"
            label="IP地址"
            width="140"
            align="center"
          ></el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)" size="small">
                {{ getStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300" align="center">
            <template #default="scope">
              <el-button size="mini" @click="handleViewDetails(scope.row)"> 查看 </el-button>
              <el-button size="mini" type="primary" @click="handleEditDevice(scope.row)">
                编辑
              </el-button>
              <el-button size="mini" type="danger" @click="handleDeleteDevice(scope.row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
          ></el-pagination>
        </div>
      </div>
    </main>

    <!-- 新增/编辑设备弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="deviceForm" ref="deviceFormRef" :rules="formRules" label-width="120px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="deviceForm.name" placeholder="请输入设备名称"></el-input>
        </el-form-item>
        <el-form-item label="设备编码" prop="code" v-if="!isAddMode">
          <el-input v-model="deviceForm.code" disabled placeholder="设备唯一编码"></el-input>
        </el-form-item>
        <el-form-item label="设备类型" prop="type">
          <el-select v-model="deviceForm.type" placeholder="请选择设备类型">
            <el-option
              v-for="type in deviceTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安装位置" prop="location">
          <el-input v-model="deviceForm.location" placeholder="请输入安装位置"></el-input>
        </el-form-item>
        <el-form-item label="IP地址" prop="ipAddress">
          <el-input v-model="deviceForm.ipAddress" placeholder="请输入设备IP地址"></el-input>
        </el-form-item>
        <el-form-item label="MAC地址" prop="macAddress">
          <el-input v-model="deviceForm.macAddress" placeholder="请输入设备MAC地址"></el-input>
        </el-form-item>
        <el-form-item label="安装日期">
          <el-date-picker
            v-model="deviceForm.installDate"
            type="date"
            placeholder="选择安装日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDeviceForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看设备详情弹窗 -->
    <el-dialog
      title="设备详情"
      v-model="viewDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="viewDeviceForm" label-width="120px" class="view-form">
        <el-form-item label="设备名称">
          <el-input v-model="viewDeviceForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="设备编码">
          <el-input v-model="viewDeviceForm.code" disabled></el-input>
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select v-model="viewDeviceForm.type" disabled placeholder="设备类型">
            <el-option
              v-for="type in deviceTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安装位置">
          <el-input v-model="viewDeviceForm.location" disabled></el-input>
        </el-form-item>
        <el-form-item label="IP地址">
          <el-input v-model="viewDeviceForm.ipAddress" disabled></el-input>
        </el-form-item>
        <el-form-item label="MAC地址">
          <el-input v-model="viewDeviceForm.macAddress" disabled></el-input>
        </el-form-item>
        <el-form-item label="安装日期">
          <el-date-picker
            v-model="viewDeviceForm.installDate"
            type="date"
            disabled
            placeholder="安装日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-tag :type="getStatusTagType(viewDeviceForm.status)" size="small">
            {{ getStatusLabel(viewDeviceForm.status) }}
          </el-tag>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
      title="确认删除"
      v-model="deleteDialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <p>您确定要删除该设备吗？删除后将无法恢复。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 设备列表数据
const deviceList = ref([])

// 筛选表单
const filterForm = reactive({
  name: '',
  type: '',
  status: '',
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 设备类型
const deviceTypes = [
  { value: 'door_main', label: '门禁主机' },
  { value: 'reader', label: '读卡器' },
  { value: 'barrier', label: '道闸' },
  { value: 'intercom', label: '可视对讲' },
  { value: 'controller', label: '控制器' },
]

// 设备状态
const deviceStatuses = [
  { value: 'online', label: '在线', colorClass: 'stat-online', icon: 'el-icon-check' },
  { value: 'offline', label: '离线', colorClass: 'stat-offline', icon: 'el-icon-close' },
  { value: 'warning', label: '预警', colorClass: 'stat-warning', icon: 'el-icon-warning' },
  {
    value: 'maintenance',
    label: '维护中',
    colorClass: 'stat-maintenance',
    icon: 'el-icon-wrench',
  },
]

// 弹窗状态
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const viewDialogVisible = ref(false) // 查看详情弹窗状态

// 弹窗标题
const dialogTitle = ref('')

// 当前操作的设备ID
const currentDeviceId = ref(null)

// 设备表单数据
const deviceForm = reactive({
  id: '',
  name: '',
  code: '',
  type: '',
  location: '',
  ipAddress: '',
  macAddress: '',
  installDate: '',
  status: 'online',
})

// 查看详情表单数据
const viewDeviceForm = reactive({
  id: '',
  name: '',
  code: '',
  type: '',
  location: '',
  ipAddress: '',
  macAddress: '',
  installDate: '',
  status: '',
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  location: [{ required: true, message: '请输入安装位置', trigger: 'blur' }],
  ipAddress: [
    { required: true, message: '请输入IP地址', trigger: 'blur' },
    {
      pattern: /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
      message: '请输入有效的IP地址',
      trigger: 'blur',
    },
  ],
}

// 加载状态
const loading = ref(false)

// 计算属性：筛选后的设备列表
const filteredDevices = computed(() => {
  return deviceList.value.filter((device) => {
    const matchesName = device.name.toLowerCase().includes(filterForm.name.toLowerCase())
    const matchesType = !filterForm.type || device.type === filterForm.type
    const matchesStatus = !filterForm.status || device.status === filterForm.status
    return matchesName && matchesType && matchesStatus
  })
})

// 计算属性：是否为新增模式
const isAddMode = computed(() => {
  return !currentDeviceId.value
})

// 获取设备列表
const fetchDeviceList = async () => {
  loading.value = true
  try {
    // 模拟后端数据
    const mockData = [
      {
        id: '1',
        name: '1号楼门禁主机',
        code: 'DEV-2023-001',
        type: 'door_main',
        location: '1号楼1单元门口',
        ipAddress: '192.168.1.101',
        macAddress: '00:1B:44:11:3A:B7',
        installDate: '2023-03-15',
        status: 'online',
      },
      {
        id: '2',
        name: '2号楼读卡器',
        code: 'DEV-2023-002',
        type: 'reader',
        location: '2号楼2单元电梯口',
        ipAddress: '192.168.1.102',
        macAddress: '00:1B:44:11:3A:B8',
        installDate: '2023-03-20',
        status: 'online',
      },
      {
        id: '3',
        name: '地下车库道闸',
        code: 'DEV-2023-003',
        type: 'barrier',
        location: '地下车库入口',
        ipAddress: '192.168.1.103',
        macAddress: '00:1B:44:11:3A:B9',
        installDate: '2023-04-05',
        status: 'warning',
      },
      {
        id: '4',
        name: '3号楼对讲设备',
        code: 'DEV-2023-004',
        type: 'intercom',
        location: '3号楼大堂',
        ipAddress: '192.168.1.104',
        macAddress: '00:1B:44:11:3A:BA',
        installDate: '2023-05-12',
        status: 'offline',
      },
    ]

    deviceList.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('获取设备列表失败：' + (error.message || '未知错误'))
    console.error('获取设备列表失败', error)
  } finally {
    loading.value = false
  }
}

// 筛选设备
const handleFilter = () => {
  pagination.currentPage = 1
  fetchDeviceList()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.name = ''
  filterForm.type = ''
  filterForm.status = ''
  pagination.currentPage = 1
  fetchDeviceList()
}

// 处理分页大小变化
const handleSizeChange = (pageSize) => {
  pagination.pageSize = pageSize
  pagination.currentPage = 1
  fetchDeviceList()
}

// 处理当前页变化
const handleCurrentChange = (currentPage) => {
  pagination.currentPage = currentPage
  fetchDeviceList()
}

// 打开新增设备弹窗
const handleAddDevice = () => {
  dialogTitle.value = '新增设备'
  currentDeviceId.value = null
  Object.assign(deviceForm, {
    id: '',
    name: '',
    code: '',
    type: '',
    location: '',
    ipAddress: '',
    macAddress: '',
    installDate: '',
    status: 'online',
  })
  dialogVisible.value = true
}

// 打开编辑设备弹窗
const handleEditDevice = (device) => {
  dialogTitle.value = '编辑设备'
  currentDeviceId.value = device.id
  Object.assign(deviceForm, { ...device })
  dialogVisible.value = true
}

// 查看设备详情
const handleViewDetails = (device) => {
  Object.assign(viewDeviceForm, { ...device })
  viewDialogVisible.value = true
}

// 打开删除确认弹窗
const handleDeleteDevice = (id) => {
  currentDeviceId.value = id
  deleteDialogVisible.value = true
}

// 确认删除设备
const confirmDelete = async () => {
  try {
    // 前端模拟删除
    deviceList.value = deviceList.value.filter((device) => device.id !== currentDeviceId.value)
    pagination.total = deviceList.value.length

    ElMessage.success('设备删除成功')
    deleteDialogVisible.value = false
  } catch (error) {
    ElMessage.error('设备删除失败：' + (error.message || '未知错误'))
    console.error('设备删除失败', error)
  }
}

// 表单引用
const deviceFormRef = ref()

// 提交设备表单
const submitDeviceForm = async () => {
  deviceFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isAddMode.value) {
          // 前端模拟新增
          const newDevice = {
            ...deviceForm,
            id: Date.now().toString(),
            code: `DEV-${new Date().getFullYear()}-${(deviceList.value.length + 1).toString().padStart(3, '0')}`,
            status: 'online',
          }

          deviceList.value.unshift(newDevice)
          ElMessage.success('设备新增成功')
        } else {
          // 前端模拟更新
          const index = deviceList.value.findIndex((device) => device.id === currentDeviceId.value)
          if (index !== -1) {
            deviceList.value[index] = { ...deviceForm }
          }

          ElMessage.success('设备更新成功')
        }

        pagination.total = deviceList.value.length
        dialogVisible.value = false
      } catch (error) {
        const message = isAddMode.value ? '新增' : '更新'
        ElMessage.error(`设备${message}失败：` + (error.message || '未知错误'))
        console.error(`设备${message}失败`, error)
      }
    }
  })
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    online: 'success',
    offline: 'danger',
    warning: 'warning',
    maintenance: 'info',
  }
  return typeMap[status] || 'default'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const statusItem = deviceStatuses.find((item) => item.value === status)
  return statusItem ? statusItem.label : status
}

// 格式化设备类型显示
const formatDeviceType = (row) => {
  const typeItem = deviceTypes.find((item) => item.value === row.type)
  return typeItem ? typeItem.label : row.type
}

// 获取特定状态的设备数量
const getStatusCount = (status) => {
  return deviceList.value.filter((device) => device.status === status).length
}

// 页面加载时获取设备列表
onMounted(() => {
  fetchDeviceList()
})
</script>

<style scoped>
.device-management-container {
  background-color: #f5f7fa;
}

.page-header {
  background-color: #fff;
  padding: 20px 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.header-content h1 {
  font-size: 20px;
  color: #1f2329;
  margin: 0;
}

.header-content p {
  font-size: 14px;
  color: #86909c;
  margin: 5px 0 0 0;
}

.main-content {
  padding: 20px 30px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-and-actions {
  width: 100%;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  gap: 15px;

  > * {
    width: 100%;
  }

  .row {
    display: flex;
    flex-direction: row;
    gap: 16px;
  }
}

.filter-item {
  min-width: 140px;
}

.add-device-btn {
  white-space: nowrap;
}

.status-stats {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.stat-card {
  height: 64px;
  flex: 1;
  min-width: 150px;
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.stat-online {
  border-left: 4px solid #52c41a;
}

.stat-offline {
  border-left: 4px solid #f5222d;
}

.stat-warning {
  border-left: 4px solid #faad14;
}

.stat-maintenance {
  border-left: 4px solid #1890ff;
}

.stat-info .stat-label {
  font-size: 14px;
  color: #86909c;
  margin: 0 0 5px 0;
}

.stat-info .stat-count {
  font-size: 20px;
  font-weight: 600;
  color: #1f2329;
  margin: 0;
}

.stat-icon {
  font-size: 24px;
}

.stat-online .stat-icon {
  color: #52c41a;
}

.stat-offline .stat-icon {
  color: #f5222d;
}

.stat-warning .stat-icon {
  color: #faad14;
}

.stat-maintenance .stat-icon {
  color: #1890ff;
}

.device-table-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 15px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

/* 查看详情表单样式 */
.view-form .el-form-item {
  margin-bottom: 16px;
}

.view-form + .dialog-footer {
  text-align: center;
}
</style>
